<template>
  <view class="goodsCar">
    <view class="car-content">
      <u-swipe-action
        v-for="(item, index) in goodList"
        :show="item.show"
        :vibrate-short="true"
        :index="index"
        :key="item.id"
        @click="clickGood"
        @open="openGood"
        @content-click="clickGoodContent"
        :options="options"
        style="padding-top: 0.5rem"
      >
        <view class="item u-border-bottom">

        <view style="width:1.2rem;
height:1.2rem" >
		<image
            v-if="!item.select"
            class=""
            style="width: 100%;
height: 100%;
margin-right: 0.3rem;"
            src="../../style/image/cargo/round.png"
            alt=""
          /> 
		  <image
            v-if="item.select"
            class=""
            style="width: 100%;
height: 100%;
margin-right: 0.3rem;"
            src="../../style/image/cargo/selectRound.png"
            alt=""
          />
		</view>
         
          <image style="width: 5rem;
height: 5rem;
border-radius: 0.3rem;
margin: 0.2rem;" mode="aspectFill" :src="item.posType.image" />
          <!-- 此层wrap在此为必写的，否则可能会出现标题定位错误 -->
          <view class="title-wrap">
            <view
              style="
                font-size: 0.75rem;
                font-family: PingFang SC;
                font-weight: 400;
                color: #000000;
              "
            >
              {{ item.posType.modelsName }}
            </view>
            <view class="content-bottom">
              <view
                style="
                  font-size: 1rem;
                  font-family: Myriad Pro;
                  font-weight: 300;
                  color: #ff0000;
                "
                >¥{{ item.price }}</view
              >
            </view>
          </view>
          <view>
            <u-number-box
              v-model="item.num"
              :index="item.id"
              :min="item.posTypePrice==null?1:item.posTypePrice.count"
              :step="item.posTypePrice==null?1:item.posTypePrice.count"
              @change="numberChange"
            ></u-number-box>
          </view>
        </view>
      </u-swipe-action>
    </view>
    <!-- <view class="footerB" >

        </view> -->     
    <view class="footP">
      <view
        style="
          height: 3rem;
          line-height: 3rem;
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
        "
      >
        <view
          @click="allSelectBtn"
          style="
            margin-left: 0.2rem;
            width: 40;
            display: flex;
            align-items: center;
          "
        >
        <view style="width:1.2rem;
height:1.2rem">

		 <image
            v-if="!selectAll"
            style="width: 100%; height: 100%;display: block;margin-right:0rem"
            src="../../style/image/cargo/round.png"
            alt=""
          />
          <image
            v-if="selectAll"
            style="width: 100%; height: 100%;display: block;margin-right:0rem"
            src="../../style/image/cargo/selectRound.png"
            alt=""
          />
      </view>

          <view style="margin-left:0.5rem" class="">全选</view>
        </view>

        <view @click="settlement" class="foot-right" style="margin-right: 0rem">
          <view
            style="
              font-size: 0.73rem;
              font-family: PingFang SC;
              font-weight: 300;
            "
          >
            合计:<span style="color: red">¥{{ allPrice }}</span>
          </view>
          <view class="settle">结算</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang='ts' >
import { Component, Prop, Vue, Watch, Emit } from "vue-property-decorator";
import { delCartGoods } from "../../utils/uniApi";
import { editCartGoodsNum } from "../../utils/uniApi";
import { findCartGoods } from "../../utils/uniApi";

@Component({
  //   @Component  是一个装修器   不可以在下面写语句
  name: "test",
})
export default class extends Vue {
  @Prop({
    type: String, // 父组件传递给子组件的数据类型
    required: false, // 是否必填
    default: " ", // 默认值， 如果传入的是 Object，则要 default: ()=>({}) 参数为函数
  })
  msg!: string;

  disabled = false;
  btnWidth = 180;
  show = false;
  selectAll = false;
  public goodList: any = [];
  public allPrice: any = 0.0; //购物车商品总价
  options = [
    {
      text: "删除",
      style: {
        backgroundColor: "#dd524d",
      },
    },
  ];

  created() {}

  onHide() {
    uni.hideLoading();
  }
  
  //下拉刷新
  onPullDownRefresh() {
      setTimeout(function () {
        uni.redirectTo({
          url: "../../pages/buy/goodsCar",
        });
        uni.stopPullDownRefresh();
      }, 1000);
  }

  mounted() {
    //  console.log('父组件传递的参数:',this.$parent)   //暂时不考虑

    // uni.navigateTo({
    //   url: "./selectBusin",
    // });
    this.findCartGoods();
  }

  //拉取购物车的数据
  findCartGoods() {
    uni.showLoading({
      title: "加载中",
    });
    let params = {
      pageNo: 1,
      pageSize: 100,
      userId:
        uni.getStorageSync("userId") == ""
          ? ""
          : parseInt(uni.getStorageSync("userId")),
    };
    findCartGoods(params).then((res: any) => {
      // console.log('++++++++++++++++++++购物车的数据列表：' + JSON.stringify(res.data.data.data) )
      if (res.data.code == 200) {
        for (let entry of res.data.data.data) {
          entry.show = false;
          entry.select = false;
        }
        this.goodList = res.data.data.data;
        uni.hideLoading();
      } else {
        uni.hideLoading();
        uni.showToast({
          title: "数据加载失败",
          icon: "none",
          duration: 2000,
        });
      }
    });
  }

  //左滑  操作列表（目前只有删除功能）
  clickGood(index: any, index1: any) {
    // console.log('1输出clickGood值：'+index)
    // console.log('2输出clickGood值：'+index1)
    if (index1 == 0) {
      //第一个参数为商品索引   第二个参数未删除选项的索引（只有删除一项  索引未0）
      uni.showLoading({
        title: "加载中",
      });
      let params = {
        goodsCartId: this.goodList[index].id,
        userId:
          uni.getStorageSync("userId") == ""
            ? ""
            : parseInt(uni.getStorageSync("userId")),
      };
      delCartGoods(params).then((res: any) => {
        // console.log('++++++++++++++++++++购物车删除：' + JSON.stringify(res.data) )
        if (res.data.code == 200) {
          this.goodList.splice(index, 1);
          this.allPrice = this.allPriceMethod(this.goodList);
          uni.hideLoading();
          uni.showToast({
            title: "删除成功",
            icon: "none",
            duration: 2000,
          });
        } else {
          uni.hideLoading();
          uni.showToast({
            title: "删除失败，请重试",
            icon: "none",
            duration: 2000,
          });
        }
      });
    }
  }
  //左滑按钮
  openGood(index: any) {
    console.log("输出openGood值：" + index);
    //    先将正在被操作的swipeAction标记为打开状态，否则由于props的特性限制，
    // 原本为'false'，再次设置为'false'会无效
    this.goodList[index].show = true;
    this.goodList.map((val: any, idx: any) => {
      if (index != idx) this.goodList[idx].show = false;
    });
  }
  //点击内容  选中
  clickGoodContent(index: any) {
    // console.log('输出clickGoodContent值：'+index)

    this.goodList[index].select = !this.goodList[index].select;
    this.allPrice = this.allPriceMethod(this.goodList);

    var isall: any = true;
    this.goodList.map((val: any, idx: any) => {
      if (this.goodList[idx].select == false) isall = false;
    });
    if (isall && !this.selectAll) {
      this.selectAll = true;
    } else {
      this.selectAll = false;
    }
  }

  //全选按钮
  allSelectBtn() {
    this.selectAll = !this.selectAll;
    if (this.selectAll) {
      for (let entry of this.goodList) {
        entry.select = true;
      }
    } else {
      for (let entry of this.goodList) {
        entry.select = false;
      }
    }
    this.allPrice = this.allPriceMethod(this.goodList);
  }

  //合计金额
  allPriceMethod(list: any) {
    var all: any = 0.0;
    for (let entry of list) {
      if (entry.select) {
        all = all + entry.num * entry.price;
      }
    }
    return all.toFixed(2);
  }
  //数字步进器
  numberChange(value: any) {
    // console.log('+++++++输出valChange值：'+JSON.stringify(value))
    // uni.showLoading({
    // 	title: '加载中'
    // });
    let params = {
      num: value.value,
      goodsCartId: value.index,
      userId:
        uni.getStorageSync("userId") == ""
          ? ""
          : parseInt(uni.getStorageSync("userId")),
    };
    editCartGoodsNum(params).then((res: any) => {
      console.log(
        "++++++++++++++++++++修改购物车的数量：" + JSON.stringify(res.data)
      );
      if (res.data.code == 200) {
        if (this.goodList.length > 0) {
          for (var i = 0; i < this.goodList.length; i++) {
            var item = this.goodList[i];
            if (item.id == value.index) {
              item.num = value.value;
            }
          }
          this.allPrice = this.allPriceMethod(this.goodList);
        }
        // uni.hideLoading();
      } else {
        // uni.hideLoading();
      }
    });
  }

  //结算按钮
  settlement() {
    var isHaveSelect = false;
    var selectList: any = [];
    this.goodList.map((val: any, idx: any) => {
      if (val.select) {
        isHaveSelect = true;
        selectList.push(val);
      }
    });
    if (isHaveSelect) {
      let goodsDic = { list: selectList, all: this.allPrice };
      uni.navigateTo({
        url:
          "../order/sureOrder?goods=" +
          encodeURIComponent(JSON.stringify(goodsDic)),
      });
    } else {
      uni.showToast({
        title: "请选择商品再去结算",
        icon: "none",
        duration: 2000,
      });
    }
  }
}
</script>


<style  lang="scss"  scoped>
/* >>> .title-wrap {   !!!
  width: 100%;
} */

// /deep/uni-image {
//  width:320px;
//  height:240px;
//  /*! display:inline-block; */overflow:hidden;
//  position:relative
// }


.item {
  display: flex;
  padding: 20rpx;
  align-items: center;
}

image {
//   width: 120rpx;
//   flex: 0 0 120rpx;
//   height: 120rpx;
//   margin-right: 20rpx;
//   border-radius: 12rpx;
}

.title {
  text-align: left;
  font-size: 28rpx;
  margin-top: 20rpx;
}

.content-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goodsCar {
  background-color: #f4f5f7;
  height: 88vh;
}

.footP {
  position: fixed;
  bottom: 0;
  background-color: white;
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.content-bottom {
  margin: 1rem;
}

.car-content {
  padding: 0rem 0.5rem 0.5rem 0.5rem;
  background-color: #f4f5f7;
  margin-bottom: 3rem;
}

.foot-right {
  display: flex;
   }

.settle {
  background-color: #02af74;
  height: 100%;
  width: 5rem;
  text-align: center;
  font-size: 0.8rem;
  font-family: PingFang SC;
  font-weight: 400;
  color: white;
  margin-left: 1rem;
}

.image1 {
  margin-right: 0.3rem;
  width: 1rem !important;
  height: 1rem;
}
</style>